<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row>
          <a-col :span="8">
            <a-form-item label="车场选择">
              <a-select
                @change="parkCodeChange"
                v-decorator="['parkCode', {}]"
                :options="parkCodeList"
                v-model="parkCode"
                :disabled="isGrey"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-item label="月租套餐">
              <a-select
                v-decorator="['packageId', { rules: [{ required: true, message: '请选择月租套餐!' }] }]"
                @select=""
                :options="monthlyPackageInfoList"
                v-model="packageId"
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-item label="通行权限">
              <a-select
                @change="permissionGroupChange"
                v-decorator="['throughAuthorityId', { rules: [{ required: true, message: '请选择通行权限!' }] }]"
                :options="permissionGroupList"
                v-model="throughAuthorityId"
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-item label="部门/组织">
              <a-tree-select
                v-model="deptId"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="departTree"
                tree-default-expand-all
              >
              </a-tree-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col>
            <a-form-item label="自动分配月租车位" prop="delivery">
              <a-switch v-model="form.delivery" @click="deliveryClick"/>
              <span style="color: red; padding-left: 20px"
                >提示：月租文件无需填写车位号，系统根据车牌号，自动分配未绑定车位。分配车位数以月租套餐类型为准，这种选择只能在单区域下使用。</span
              >
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-item label="车场区域" v-if="areaHide">
              <a-select
                v-decorator="['areaId', { rules: [{ required: true, message: '请选择区域!' }] }]"
                :options="areaList"
                v-model="areaId"
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="7" style="margin-bottom: 10px">
            <div class="clearfix" style="float: left">
              <a-upload
                :file="fileList"
                :remove="handleRemove"
                :beforeUpload="beforeUpload"
                accept=".xls"
                :multiple="true"
              >
                <a-button> <a-icon type="upload" /> 选择月租文件 </a-button>
              </a-upload>
            </div>
            <div>
              <a-button style="float: right" @click="downloadTemp('月租车导入模板')">
                <a-icon type="download" /> 点击下载模板
              </a-button>
            </div>
          </a-col>
        </a-row>

        <a-row>
          <a-col>
            <div>
              <a-button
                type="primary"
                @click="fileInspect"
                :disabled="fileList.length === 0"
                :loading="uploading"
                style="margin-top: 16px"
              >
                {{ uploading ? '上传中' : '文件检查' }}
              </a-button>
              <a-button
                type="primary"
                @click="handleUpload"
                :disabled="fileList.length === 0"
                :loading="uploading"
                style="margin-top: 16px; margin-left: 20px"
              >
                {{ uploading ? '上传中' : '开始导入' }}
              </a-button>
              <span style="color: red; padding-left: 20px">说明：导入文件表格中的数据最大为500条。</span>
            </div>

            <div class="export-loading" v-if="showImport">
              <div class="export-con">
                <span class="export-title">{{ this.importText }}</span>
                <a-progress
                  :strokeWidth="15"
                  stroke-linecap="square"
                  :show-info="false"
                  :percent="percent"
                  status="active"
                  strokeColor="#c43b3b"
                />
              </div>
            </div>
            <br />
          </a-col>
        </a-row>

        <a-row>
          <a-col>
            <div>
              <a-radio-group :default-value="1" v-model="isCover">
                <a-radio :value="1"> 忽略重复（以已存在记录为准） </a-radio>
                <a-radio :value="2"> 覆盖导入（以最新记录为准） </a-radio>
              </a-radio-group>
            </div>
            <br />
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      >
      </a-table>
    </div>
    <!-- table区域-end -->
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { downFile, getAction, postAction } from '@/api/manage'
import { getMonthlyParkInfoList } from '@api/api'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import Vue from 'vue'
import { axios } from '@/utils/request'

export default {
  name: 'MonthlyCardInfoImport',
  mixins: [JeecgListMixin],

  components: {},

  data() {
    return {
      description: '月卡信息导入页面',
      percent: 0,
      showImport: false,
      departTree: [],
      fileList: [],
      dataSource: [],
      uploading: false,
      value: undefined,
      form: {
        name: '',
        region: undefined,
        date1: undefined,
        delivery: false,
        type: [],
        resource: '',
        desc: '',
      },
      // 表头
      columns: [
        {
          title: '行号',
          align: 'center',
          dataIndex: 'number',
        },
        {
          title: '车牌号',
          align: 'center',
          // width: 120,
          dataIndex: 'plateNo',
        },
        {
          title: '车位信息',
          align: 'center',
          // width: 120,
          dataIndex: 'parkNumbers',
        },
        {
          title: '起始时间',
          align: 'center',
          // width: 80,
          dataIndex: 'startTime',
        },
        {
          title: '到期时间',
          align: 'center',
          // width: 120,
          dataIndex: 'endTime',
        },
        {
          title: '金额（元）',
          align: 'center',
          // width: 120,
          dataIndex: 'money',
        },
        {
          title: '车主/姓名',
          align: 'center',
          // width: 100,
          dataIndex: 'ownerName',
        },
        {
          title: '手机号码',
          align: 'center',
          // width: 150,
          dataIndex: 'phoneNumber',
        },
        {
          title: '住房/房号',
          align: 'center',
          // width: 120,
          dataIndex: 'roomNumber',
        },

        {
          title: '验证是否成功',
          align: 'center',
          // width: 150,
          dataIndex: 'isErrorStr',
          customRender: (x) => {
            if (0 === x) {
              return <span style="color:red;">错误</span>
            } else if (1 === x) {
              return <span style="color:green;">正确</span>
            }
          },
        },
        {
          title: '原因',
          align: 'center',
          // width: 150,
          dataIndex: 'remarks',
        },
      ],
      url: {
        importExcelUrl: 'monthlyCardInfo/importExcel',
        getPermissionGroupList: '/permissionGroup/getPermissionGroup',
        getDepartmentList: '/monthlyDepartment/queryTreeList',
        getMonthlyPackageList: '/monthlyPackageInfo/getMonthlyPackageInfoList',
        getPackageInfo: '/monthlyPackageInfo/queryById',
        queryByPermissionIdAreaList: '/area/parkAreaInfo/queryByPermissionIdAreaList',
        downloadTemp: '/monthlyCardInfo/downloadTemp',
        fileInspect: '/monthlyCardInfo/fileInspect',
        importExcel: '/monthlyCardInfo/importExcel',
      },
      isorter: {
        column: 'monthly_card_info.createTime',
        order: 'desc',
      },
      monthlyPackageInfoList: [],
      permissionGroupList: [],

      parkCodeList: [],
      parkCode: '',
      packageId: '',
      throughAuthorityId: '',
      deptId: '',
      areaList: [],
      areaId: '',
      isCover: 1,
      isGrey: true,
      areaHide:false,

      lockReconnect: false, //是否真正建立连接
      timeout: 5 * 1000, //5秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutnum: null, //断开 重连倒计时
      importText: '正在检查',
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  created() {
    this.keyupEnter()
    this.initParkInfo()
  },
  methods: {
    deliveryClick(value){
      this.areaHide = value;
      console.log("点击值 ",value);
    },

    // 月租车模板下载
    downloadTemp(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      return new Promise((resolve, reject) => {
        let { error, values, startTime } = this.beforeExportExcel()
        if (!!error && this.selectedRowKeys.length == 0) {
          this.$message.error(error)
          reject(error)
        } else {
          if (!!startTime) {
            fileName = startTime + '_' + fileName
          }
          downFile(this.url.downloadTemp, {
            targetFileName: fileName,
          }).then((data, v, i) => {
            if (!data) {
              this.$message.warning('文件下载失败')
              return
            }
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
              window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
            } else {
              let url = window.URL.createObjectURL(new Blob([data]))
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', fileName + '.xls')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link) //下载完成移除元素
              window.URL.revokeObjectURL(url) //释放掉blob对象
            }
          })
          resolve(values)
        }
      })
    },

    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file]
      return false
    },

    // 检查文件
    fileInspect() {
      if (this.fileList.length > 1) {
        this.$message.error('只能上传一个文件')
        return
      }
      if (this.packageId == null || this.packageId == '' || this.packageId == 'undefined') {
        this.$message.error('请选择月卡套餐')
        return
      }
      if (this.deptId == null || this.deptId == '' || this.deptId == 'undefined') {
        this.$message.error('请选择部门组织')
        return
      }
      if (this.areaId == null || this.areaId == '' || this.areaId == 'undefined') {
        this.$message.error('请选择区域')
        return
      }
      this.dataSource = []
      this.showImport = true
      this.importText = '正在检查'
      // 建立websocket连接
      this.initWebSocket()
      const { fileList } = this
      const formData = new FormData()
      fileList.forEach((file) => {
        formData.append('file', file)
      })
      formData.append('parkCode', this.parkCode)
      formData.append('packageId', this.packageId)
      formData.append('throughAuthorityId', this.throughAuthorityId)
      formData.append('deptId', this.deptId)
      formData.append('areaId', this.areaId)
      formData.append('isAutoPark', this.form.delivery ? 1 : 0)
      formData.append('ignoreOrCover', this.isCover)
      // postAction(this.url.fileInspect, formData).then((res) => {
      //   if (res.success) {
      //     this.timer = setTimeout(() => {
      //       //设置延迟执行
      //       this.showImport = false
      //       this.$message.success('检查完成')
      //     }, 3000)
      //     //this.websock.onclose = this.websocketclose;
      //     return
      //   }
      //   if (res.code === 520) {
      //     this.$message.error(res.message)
      //   }
      //   this.showImport = false
      // })
      let that = this;
      axios
        .post(
          //请求方式
          this.url.fileInspect, //接口地址
          formData, //传递参数
          { timeout: 3600000 }
        ) //设置超时，单位毫秒
        .then(function (res) {
          if (res.success) {
            that.timer = setTimeout(()=>{   //设置延迟执行
              that.showImport = false;
              that.percent = 0;
              that.$message.success('检查完成')
            },1000);
          }else{
            that.showImport = false;
            that.percent = 0;
            that.$message.error(res.message)
          }   
          
        })
        .catch((error) => {
          this.showImport = false;
          this.percent = 0;
          this.$message.error('检查失败')
          console.log(error)
        })

    },

    //初始化weosocket
    initWebSocket() {
      if (typeof WebSocket === 'undefined') {
        alert('您的浏览器不支持WebSocket')
        return false
      }
      let token = Vue.ls.get(ACCESS_TOKEN),
        _self = this
      const ishttps = 'https:' == document.location.protocol ? true : false
      console.log('是否为HTTPS' + ishttps)
      var ip = window.document.domain
      let wsuri = ''
      if (ishttps) {
        console.log('HTTPS请求' + ishttps)
        wsuri = 'wss://' + ip + '/park-single/monthlyWebSocket/' + token
      } else {
        console.log('HTTP请求' + ishttps)
        wsuri = 'ws://' + ip + ':8099/park-single/monthlyWebSocket/' + token
      }

      console.log('wensocket请求地址 = ' + wsuri)
      this.websock = new WebSocket(wsuri)
      this.websock.onopen = this.websocketonopen
      //接收后端返回的数据
      this.websock.onmessage = function (e) {
        var data = JSON.parse(e.data)
        _self.percent = parseInt(data.percentage)
        if (data.data != 'null') {
          _self.dataSource.push(JSON.parse(data.data))
        }
        //收到服务器信息，心跳重置
        _self.reset()
      }

      this.websock.onerror = this.websocketonerror
      //this.websock.onclose = this.websocketclose;
    },

    reset() {
      //重置心跳
      console.log('123123')
      var that = this
      //清除时间
      clearTimeout(that.timeoutObj)
      clearTimeout(that.serverTimeoutObj)
      //重启心跳
      that.start()
    },

    start() {
      //开启心跳
      var self = this
      self.timeoutObj && clearTimeout(self.timeoutObj)
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
      self.timeoutObj = setTimeout(function () {
        //这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (self.websock.readyState == 1) {
          //如果连接正常
          //self.websock.send('heartCheck')
        } else {
          //否则重连
          self.reconnect()
        }
        self.serverTimeoutObj = setTimeout(function () {
          //超时关闭
          self.websock.close()
        }, self.timeout)
      }, self.timeout)
    },

    //连接成功
    websocketonopen() {
      console.log('WebSocket连接成功')
      //开启心跳
      this.start()
    },

    //连接建立失败重连
    websocketonerror(e) {
      console.log('连接失败的信息：', e)
      //this.initWebSocket(); // 连接失败后尝试重新连接
      this.reconnect()
    },

    reconnect() {
      //重新连接
      var that = this
      if (that.lockReconnect) {
        return
      }
      that.lockReconnect = true
      //没连接上会一直重连，设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum)
      that.timeoutnum = setTimeout(function () {
        //新连接
        that.initWebSocket()
        that.lockReconnect = false
      }, 5000)
    },

    //关闭连接
    websocketclose(e) {
      console.log('断开连接', e)
      this.showImport = false
      this.percent = 0;
    },

    handleUpload() {
      if (this.fileList.length > 1) {
        this.$message.error('只能上传一个文件')
        return
      }
      if (this.packageId == null || this.packageId == '' || this.packageId == 'undefined') {
        this.$message.error('请选择月卡套餐')
        return
      }
      if (this.deptId == null || this.deptId == '' || this.deptId == 'undefined') {
        this.$message.error('请选择部门组织')
        return
      }
      if (this.areaId == null || this.areaId == '' || this.areaId == 'undefined') {
        this.$message.error('请选择车场区域')
        return
      }
      ;(this.importText = '正在导入'), (this.dataSource = [])
      this.showImport = true
      // 建立websocket连接
      this.initWebSocket()
      const { fileList } = this
      const formData = new FormData()
      fileList.forEach((file) => {
        formData.append('file', file)
      })
      formData.append('parkCode', this.parkCode)
      formData.append('packageId', this.packageId)
      formData.append('throughAuthorityId', this.throughAuthorityId)
      formData.append('deptId', this.deptId)
      formData.append('areaId', this.areaId)
      formData.append('isAutoPark', this.form.delivery ? 1 : 0)
      formData.append('ignoreOrCover', this.isCover)
      let that = this;
      axios
        .post(
          //请求方式
          this.url.importExcel, //接口地址
          formData, //传递参数
          { timeout: 3600000 }
        ) //设置超时，单位毫秒
        .then(function (res) {
          if (res.success) {
            that.timer = setTimeout(()=>{   //设置延迟执行
              that.showImport = false;
              that.percent = 0;
              that.$message.success('导入完成')
            },1000);
          }else{
            that.showImport = false;
            that.percent = 0;
            that.$message.error(res.message)
          }
          
        })
        .catch((error) => {
          this.showImport = false;
          that.percent = 0;
          this.$message.success('导入失败')
          console.log('error')
        })
    },

    initParkInfo() {
      const that = this
      getMonthlyParkInfoList().then((res) => {
        if (res.success) {
          that.parkCodeList = []
          res.result.forEach((parkInfo) => {
            that.parkCodeList.push({
              value: String(parkInfo.parkCode),
              label: parkInfo.parkName,
            })
          })
          if (that.parkCodeList.length > 0) {
            that.parkCode = that.parkCodeList[0].value
            that.parkCodeChange(that.parkCode)
          }
        }
      })
    },

    // 车场编号改变
    parkCodeChange(value, b) {
      this.initMonthlyPackageInfoList(value)
      this.loadDepartmentTreeList(value)
      this.loadPermissionGroupList(value)
    },

    // 权限组选中事件
    permissionGroupChange(value, b) {
      this.getAreaList(value)
    },

    // 初始化月卡套餐
    initMonthlyPackageInfoList(parkCode) {
      if (!parkCode) {
        return
      }
      const that = this
      that.confirmLoading = true
      getAction(this.url.getMonthlyPackageList, { parkCode: parkCode }).then((res) => {
        if (res.success) {
          that.monthlyPackageInfoList = []
          if (res.result) {
            that.monthlyPackageInfoList = res.result
            that.monthlyPackageInfoList.forEach((packageInfo) => {
              packageInfo.value = packageInfo.id
              packageInfo.label = packageInfo.packageName
            })
            if (that.monthlyPackageInfoList.length > 0) {
              this.packageId = that.monthlyPackageInfoList[0].value
            }
          }
        }
        that.confirmLoading = false
      })
    },

    loadPermissionGroupList(parkCode) {
      const that = this
      if (!parkCode) {
        return
      }
      getAction(this.url.getPermissionGroupList, { parkCode: parkCode }).then((res) => {
        if (res.success) {
          //that.permissionGroupList = []
          that.permissionGroupList = [{ value: '', label: '默认全部权限' }]
          res.result.forEach((permissionGroup) => {
            that.permissionGroupList.push({
              label: permissionGroup.permissionName,
              value: permissionGroup.id,
            })
            if (that.permissionGroupList.length <= 1) {
              this.form.setFieldsValue({ throughAuthorityId: '' })
              this.form.setFieldsValue({ throughAuthorityName: '默认全部权限' })
            } else {
              this.throughAuthorityId = that.permissionGroupList[0].value
            }
            this.getAreaList(this.throughAuthorityId)
            // if(that.permissionGroupList.length > 0){
            //   this.throughAuthorityId = that.permissionGroupList[0].value
            //   this.getAreaList(this.throughAuthorityId)
            // }
          })
        }
      })
    },

    // 根据权限组ID查询区域信息
    getAreaList(throughAuthorityId) {
      const that = this
      getAction(this.url.queryByPermissionIdAreaList + '?id=' + throughAuthorityId).then((res) => {
        if (res.success) {
          that.areaList = []
          res.result.forEach((areaInfo) => {
            that.areaList.push({
              value: areaInfo.id,
              label: areaInfo.areaName,
            })
            if (that.areaList.length > 0) {
              this.areaId = that.areaList[0].value
            }
          })
        }
      })
    },

    loadDepartmentTreeList(parkCode) {
      if (!parkCode) {
        return
      }
      postAction(this.url.getDepartmentList, { parkCode: parkCode }).then((res) => {
        if (res.success) {
          this.departTree = res.result
        }
        if (this.departTree.length > 0) {
          this.deptId = this.departTree[0].id
        }
      })
    },

    keyupEnter() {
      document.onkeydown = (e) => {
        let body = document.getElementsByTagName('body')[0]
        if (e.keyCode === 13) {
          this.loadData(1)
        }
      }
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
/* tile uploaded pictures */
.upload-list-inline >>> .ant-upload-list-item {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.upload-list-inline >>> .ant-upload-animate-enter {
  animation-name: uploadAnimateInlineIn;
}
.upload-list-inline >>> .ant-upload-animate-leave {
  animation-name: uploadAnimateInlineOut;
}
.export-loading {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1000;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.45);
}
.export-con {
  width: 380px;
  height: 50px;
  padding: 13px 15px 0px 80px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -25px;
  margin-left: -190px;
  background: rgb(244, 248, 246);
  border-radius: 5px;
  text-align: center;
}
.export-title {
  position: absolute;
  left: 15px;
  top: 13px;
}
.ant-progress-inner {
  background-color: #36cf4f;
}
element.style {
  width: 100%;
  height: 15px;
  background: rgb(31, 180, 93) !important;
  border-radius: 0px;
}
</style>